// headerBus.ts
import type { AsyncFunction } from '@/declare/common'

const beforeRouteToEvents: AsyncFunction<any>[] = []

export const headerBus = {
  onBeforeRouteTo: (fn: AsyncFunction<any>) => {
    if (!beforeRouteToEvents.includes(fn)) {
      beforeRouteToEvents.push(fn)
    }
  },
  offBeforeRouteTo: (fn: AsyncFunction<any>) => {
    const index = beforeRouteToEvents.indexOf(fn)
    if (index !== -1) {
      beforeRouteToEvents.splice(index, 1)
    }
  },
  emitBeforeRouteTo: async () => {
    for (const fn of beforeRouteToEvents) {
      await fn()
    }
  }
}
// useHeaderBusBeforeRouteTo.ts
import { onMounted, onUnmounted } from 'vue'

export const useHeaderBusBeforeRouteTo = (fn: AsyncFunction<any>) => {
  onMounted(() => {
    headerBus.onBeforeRouteTo(fn)
  })
  onUnmounted(() => {
    headerBus.offBeforeRouteTo(fn)
  })
}
